<template>
  <div>
    <div class="div1">
      <div style="width:40%;height:100%;float:left;">
        <div class="div3">
          <div class="span1">{{ currentTime }}</div>
          <div class="span1">入场人数：{{ onlineNumber }}</div>
          <div class="span1">卡号：{{ userInfoList.membershipCardNumber }}</div>
        </div>
        <div class="div2">
          <ImagePreview :src="String(memberUserPhoto1)" style="width: 100%;height: 100%;"></ImagePreview>
        </div>
      </div>
      <div style="width:1%;height:100%;float:left;display: flex;align-items: center;">
        <div style="width:2px;height:85%;background-color:rgb(183, 182, 182);"></div>
      </div>
      <div style="width:59%;height:100%;float:left;">
        <div class="div4">
          <!--          <el-button type="primary" plain style="margin-left:5%;width:8vw;height:5vh;" @click="memberEnter">会员入驻-->
          <!--          </el-button>-->
        </div>
        <div class="div5">
          <div class="div6">
            <div class="span2">{{ userInfoList.memberUserRealName }}</div>
            <div class="span3">
              性别：{{ userInfoList.memberUserSex === 0 ? '男' : userInfoList.memberUserSex === 1 ? '女' : '' }}
            </div>
            <div class="span3">手机号码：{{ userInfoList.memberUserPhone }}</div>
            <div class="span3">
              是否有私教课：
              <span>{{ ifPersonalTrainer }}</span>
              <!--              <span v-if="userInfoList.reservationList && userInfoList.reservationList.length > 0">-->
              <!--                              是-->
              <!--                            </span>-->
              <!--              <span v-else-if="userInfoList.reservationList === undefined">-->
              <!--                              &lt;!&ndash; 空的情况，不显示任何内容 &ndash;&gt;-->
              <!--                            </span>-->
              <!--              <span v-else style="color: red;">-->
              <!--                              否-->
              <!--                            </span>-->
            </div>
            <div class="span3">
              服务教练：
              <template v-for="(coach, index) in coachNames">
                <span>{{ coach.coachName }}</span>
                <span v-if="index !== coachNames.length - 1">、</span>
              </template>
            </div>
          </div>
          <div class="div7">
            <div class="span3">会员卡名称：{{ userInfoList.memberTypeName }}</div>
            <div class="span3">
              卡类型：{{ userInfoList.memberType !== undefined ? userInfoList.memberType === 0 ? '次卡' : '期限卡' : '' }}
            </div>
            <div class="span3">剩余次数：{{
                userInfoList.availableFrequency
              }}
            </div>
            <div class="span3">购卡日期：{{ formattedCreateDate }}</div>
            <div class="span3">开卡日期：{{ formattedCreateDate }}</div>
            <div class="span3">截止日期：{{ formattedRcreateDate }}</div>
          </div>
          <div
            style="font-size:200px;margin-left:70%;color:rgba(252, 185, 0);transform: translate(20%, -10%) skew(-30deg);opacity: 0.5;text-shadow: 3px 3px 4px rgba(0, 0, 0, 0.5);">
            VIP
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  selectUserInfoByNumid,
  selectEntranceNumbers,
  userIfEntrance,
  selectIfPersonalTrainer
} from "@/api/swipingCard/index"

export default {
  data() {
    return {
      currentTime: '',
      venueUniqueIdentifier: '',
      receivedMessage: "",
      userInfoList: "",
      memberUserPhoto1: "",
      formattedRcreateDate: '',
      formattedCreateDate: '',
      onlineNumber: 0,
      //是否有私教课
      ifPersonalTrainer: '',
      //教练名称
      coachNames: [],
    };
  },
  watch: {
    // 在 receivedMessage 变化时执行指定的方法
    receivedMessage(newVal) {
      this.handleReceivedMessage(newVal);
      console.log(newVal)
      this.coachNames = []
    }
  },
  created() {

    // 首次加载时立即获取系统时间
    this.updateTime();
    //查询当天入场人数
    this.selectEntranceNumber();
    // 每秒更新一次时间
    setInterval(this.updateTime, 1000);
    // 在页面进入时创建 WebSocket 连接
    this.ws = new WebSocket('ws://localhost:8080/wsReadCard/123123');
    // 监听 WebSocket 连接打开事件
    this.ws.onopen = () => {
      console.log('WebSocket connected');
    };

    // 监听 WebSocket 收到消息事件
    this.ws.onmessage = (event) => {
      this.receivedMessage = event.data;
    };
  },
  methods: {
    // 跳转页面
    memberEnter() {
      this.$router.push('/member/memberUserInfo')
    },
    //查询当天入场人数
    selectEntranceNumber() {
      const currentDateTime = new Date();
      const currentDate = this.formatDateVenue(currentDateTime)
      selectEntranceNumbers(currentDate).then((res) => {
        if (res.data > 0) {
          this.onlineNumber = res.data
        } else {
          this.onlineNumber = 0;
        }
      })
    },
    formatDateVenue(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // websocket数据变化时进行查询
    handleReceivedMessage(message) {
      this.userInfoList = {}
      this.formattedCreateDate = ''
      this.formattedRcreateDate = ''
      this.memberUserPhoto1 = ""
      this.onlineNumber = ""
      const parsedMessage = JSON.parse(message);
      //卡号
      const membershipCardNumber = parsedMessage.cardNum;
      //查询会员当天是否入场
      userIfEntrance(membershipCardNumber).then((res) => {
        if (res.data === 1) {
          this.$message({type: "success", message: "您已入场"});
          this.getMemberInfo(membershipCardNumber)
        } else {
          this.$notify.error({title: '警告', message: res.msg})
          this.getMemberInfo(membershipCardNumber)
        }
        //查询入场人数
        this.selectEntranceNumber()
      }),
        //查询是否有私教
        selectIfPersonalTrainer(membershipCardNumber).then((res) => {
          const count = res.data.length;
          if (count > 0) {
            this.ifPersonalTrainer = "是"
          } else {
            this.ifPersonalTrainer = "否"
          }
          const seen = new Set();

          res.data.forEach((obj, index) => {
            // 如果 Set 中没有这个教练名称，则添加到 coachNames 数组和 Set 中
            if (!seen.has(obj.coachName)) {
              this.coachNames.push({id: this.coachNames.length + 1, coachName: obj.coachName});
              seen.add(obj.coachName);
            }
          });
        })
    },
    //刷卡获取用户会员信息
    getMemberInfo(membershipCardNumber) {
      selectUserInfoByNumid(membershipCardNumber).then((res) => {
        if (res.data == null && res.data === undefined) {
          //会员卡未绑定用户，无操作
        } else {
          this.userInfoList = res.data
          this.memberUserPhoto1 = res.data.memberUserPhoto
          this.venueUniqueIdentifier = res.data.venueUniqueIdentifier
          // 将时间戳转换为日期对象
          console.log(this.userInfoList)
          const createTimeTimestamp = this.userInfoList.createTime;
          const createDate = new Date(createTimeTimestamp);
          // 获取日期和时间信息
          const createYear = createDate.getFullYear(); // 年份
          const createMonth = createDate.getMonth() + 1; // 月份（注意需要加1，因为月份从0开始）
          const createDay = createDate.getDate(); // 日期

          this.formattedCreateDate = `${createYear}-${createMonth}-${createDay}`; // 格式化后的日期字符串
          if (this.userInfoList.memberType === 0) {
            this.formattedRcreateDate = "..."
          } else {
            this.userInfoList.availableFrequency = "...";
            //剩余天数
            const cardDays = this.userInfoList.cardDays;
            // 获取当前时间
            const currentDate = new Date();
            const cardDaysInMillis = cardDays * 24 * 60 * 60 * 1000;
            // 计算截止时间
            const deadline = new Date(currentDate.getTime() + cardDaysInMillis);
            // 格式化截止时间（可选）
            const year = deadline.getFullYear();
            const month = String(deadline.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(deadline.getDate()).padStart(2, '0');

            const formattedDeadline = `${year}-${month}-${day}`;
            this.formattedRcreateDate = formattedDeadline// 格式化后的日期字符串
          }
        }
      })
    },
    // 修改时间
    updateTime() {
      const date = new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const hours = date.getHours();
      const minutes = date.getMinutes();
      const seconds = date.getSeconds();
      this.currentTime = `${year}年${month}月${day}日${hours}:${minutes}:${seconds}`;
    }
  }
};
</script>

<style>
.div1 {
  width: 100%;
  height: 91vh;
  background-image: url(/src/views/背景.jpg);
  background-size: cover;
}

.div2 {
  width: 30vw;
  height: 50vh;
  margin-left: 7%;
  margin-top: 5%;
  background-color: aqua;
}

.div3 {
  width: 30vw;
  height: 27vh;
  margin-left: 7%;
  margin-top: 5%;

}

.span1 {
  width: 30vw;
  height: 10vh;
  font-size: 30px;
  text-align: center;
  color: rgb(84, 78, 78);
}

.div4 {
  width: 55vw;
  height: 10vh;
  margin-top: 3%;
  margin-left: 3%;
}

.div5 {
  width: 55vw;
  height: 70vh;

}

.div6 {
  width: 25vw;
  height: 70vh;
  float: left;
}

.div7 {
  width: 30vw;
  height: 55vh;
  float: left;
}

.span2 {
  font-size: 70px;
  text-align: center;
  margin-bottom: 15%;
  margin-top: 5%;
  color: rgb(84, 78, 78);
}

.span3 {
  margin-top: 5%;
  font-size: 30px;
  margin-left: 20%;
  color: rgb(84, 78, 78);
}
</style>
